<template>
  <div class="category-ranking">
    <!-- 页面标题和描述 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h2 class="page-title">
            <n-icon :size="24" color="#18a058">
              <GridOutline />
            </n-icon>
            分类排行榜
          </h2>
          <p class="page-description">查看各分类的统计数据和热门物品排行</p>
        </div>
        
        <!-- 刷新按钮 -->
        <n-button
          type="primary"
          ghost
          :loading="loading"
          @click="() => {
            console.log('🔘 刷新按钮被点击了！');
            refreshData();
          }"
        >
          <template #icon>
            <n-icon>
              <RefreshOutline />
            </n-icon>
          </template>
          刷新数据
        </n-button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading && categories.length === 0" class="loading-container">
      <loading-skeleton :rows="6" />
    </div>

    <!-- 分类概览 -->
    <div v-else-if="!selectedCategory" class="categories-overview">
      <div class="categories-grid">
        <div
          v-for="category in categories"
          :key="category.primary_class"
          class="category-card"
          @click="selectCategory(category)"
        >
          <div class="card-header">
            <div class="category-info">
              <h3 class="category-name">{{ getCategoryDisplayName(category.primary_class) }}</h3>
              <p class="category-code">{{ category.primary_class }}</p>
            </div>
            <div class="category-icon">
              <n-icon :size="32" :color="getCategoryColor(category.primary_class)">
                <CubeOutline />
              </n-icon>
            </div>
          </div>

          <div class="card-stats">
            <div class="stat-item">
              <span class="stat-label">物品数量</span>
              <span class="stat-value">{{ category.total_items }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">子分类</span>
              <span class="stat-value">{{ category.children?.length || 0 }}</span>
            </div>
          </div>

          <div class="card-footer">
            <n-button text type="primary">
              查看详情
              <template #icon>
                <n-icon>
                  <ChevronForwardOutline />
                </n-icon>
              </template>
            </n-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分类详细排行 -->
    <div v-else class="category-detail">
      <!-- 返回按钮和分类标题 -->
      <div class="detail-header">
        <n-button
          text
          type="primary"
          @click="backToOverview"
        >
          <template #icon>
            <n-icon>
              <ArrowBackOutline />
            </n-icon>
          </template>
          返回分类概览
        </n-button>
        
        <div class="detail-title">
          <h3>{{ getCategoryDisplayName(selectedCategory.primary_class) }} - 详细排行</h3>
          <p>共 {{ selectedCategory.total_items }} 个物品</p>
        </div>
      </div>

      <!-- 筛选器 -->
      <div class="filters-section">
        <div class="filters-container">
          <div class="filters-row">
            <!-- 子分类选择器 -->
            <div v-if="selectedCategory.children && selectedCategory.children.length > 0" class="filter-item">
              <n-text class="filter-label">子分类</n-text>
              <n-select
                v-model:value="selectedSubcategory"
                :options="subcategoryOptions"
                placeholder="选择子分类（可选）"
                size="small"
                clearable
                @update:value="handleSubcategoryChange"
              />
            </div>

            <!-- 排序方式 -->
            <div class="filter-item">
              <n-text class="filter-label">排序方式</n-text>
              <n-select
                v-model:value="sortType"
                :options="sortOptions"
                placeholder="排序方式"
                size="small"
                @update:value="handleSortChange"
              />
            </div>

            <!-- 等级筛选 -->
            <div class="filter-item">
              <n-text class="filter-label">物品等级</n-text>
              <n-select
                v-model:value="gradeFilter"
                :options="gradeOptions"
                placeholder="物品等级（可选）"
                size="small"
                clearable
                @update:value="handleGradeChange"
              />
            </div>

            <!-- 时间范围 -->
            <div class="filter-item">
              <n-text class="filter-label">时间范围</n-text>
              <n-select
                v-model:value="timeRange"
                :options="timeRangeOptions"
                placeholder="时间范围"
                size="small"
                @update:value="handleTimeRangeChange"
              />
            </div>

            <!-- 刷新按钮 -->
            <div class="filter-actions">
              <n-button size="small" @click="refreshData" :loading="categoryRankingLoading">
                <template #icon>
                  <n-icon><RefreshOutline /></n-icon>
                </template>
                刷新
              </n-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 排行榜列表 -->
      <div class="ranking-list">
        <div v-if="categoryRankingLoading" class="loading-container">
          <loading-skeleton :rows="5" />
        </div>
        
        <div v-else-if="categoryRankingData.length === 0" class="empty-state">
          <n-empty description="暂无排行数据">
            <template #icon>
              <n-icon :size="48" :depth="3">
                <CubeOutline />
              </n-icon>
            </template>
          </n-empty>
        </div>

        <div v-else class="ranking-items">
          <div
            v-for="(item, index) in categoryRankingData"
            :key="item.object_id"
            class="ranking-item"
            @click="showItemDetail(item.object_id)"
          >
            <!-- 排名 -->
            <div class="rank-section">
              <div :class="getRankBadgeClass(index + 1)">
                {{ index + 1 }}
              </div>
            </div>

            <!-- 物品信息 -->
            <div class="item-info">
              <div class="item-image">
                <n-avatar
                  :size="72"
                  :src="item.image_url || item.pic"
                  fallback-src="/images/default-item.png"
                  :class="getGradeClass(item.grade)"
                />
              </div>
              
              <div class="item-details">
                <h4 class="item-name">{{ item.name }}</h4>
                <div class="item-meta">
                  <span class="item-grade">{{ getGradeText(item.grade) }}</span>
                  <span class="item-category">{{ item.second_class || item.primary_class }}</span>
                </div>
              </div>
            </div>

            <!-- 价格信息 -->
            <div class="price-section">
              <!-- 左侧：当前价格和涨跌 -->
              <div class="price-left">
                <div class="current-price">
                  <span class="price-label">当前价格</span>
                  <span class="price-value">{{ formatPrice(item.current_price) }}</span>
                </div>

                <div v-if="item.price_change !== undefined || item.price_change_percentage !== undefined" class="price-change">
                  <span :class="getPriceChangeClass(item.price_change || item.price_change_percentage || 0)" class="change-text">
                    <n-icon :size="14">
                      <ArrowUpOutline v-if="(item.price_change || item.price_change_percentage || 0) > 0" />
                      <ArrowDownOutline v-else-if="(item.price_change || item.price_change_percentage || 0) < 0" />
                      <RemoveOutline v-else />
                    </n-icon>
                    <span v-if="item.price_change !== undefined">{{ formatPriceChange(item.price_change) }}</span>
                    <span v-if="item.price_change_percentage !== undefined" class="change-percent">
                      ({{ item.price_change_percentage > 0 ? '+' : '' }}{{ item.price_change_percentage.toFixed(2) }}%)
                    </span>
                  </span>
                </div>

                <div v-if="item.previous_price" class="yesterday-price">
                  昨收: <span class="yesterday-value">{{ formatPrice(item.previous_price) }}</span>
                </div>
              </div>

              <!-- 右侧：价格对比数据 -->
              <div v-if="item.compare_to_average || item.compare_to_highest || item.compare_to_lowest || item.highest_price || item.average_price || item.lowest_price" class="price-right">
                <div v-if="item.highest_price || item.compare_to_highest" class="compare-item">
                  <span class="compare-label">最高</span>
                  <span class="compare-value">{{ formatPrice(item.highest_price || 0) }}</span>
                  <span v-if="item.compare_to_highest" :class="getPriceChangeClass(item.compare_to_highest.difference)" class="compare-percent">
                    {{ item.compare_to_highest.difference > 0 ? '+' : '' }}{{ item.compare_to_highest.percentage.toFixed(1) }}%
                  </span>
                </div>

                <div v-if="item.average_price || item.compare_to_average" class="compare-item">
                  <span class="compare-label">平均</span>
                  <span class="compare-value">{{ formatPrice(item.average_price || 0) }}</span>
                  <span v-if="item.compare_to_average" :class="getPriceChangeClass(item.compare_to_average.difference)" class="compare-percent">
                    {{ item.compare_to_average.difference > 0 ? '+' : '' }}{{ item.compare_to_average.percentage.toFixed(1) }}%
                  </span>
                </div>

                <div v-if="item.lowest_price || item.compare_to_lowest" class="compare-item">
                  <span class="compare-label">最低</span>
                  <span class="compare-value">{{ formatPrice(item.lowest_price || 0) }}</span>
                  <span v-if="item.compare_to_lowest" :class="getPriceChangeClass(item.compare_to_lowest.difference)" class="compare-percent">
                    {{ item.compare_to_lowest.difference > 0 ? '+' : '' }}{{ item.compare_to_lowest.percentage.toFixed(1) }}%
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="categoryRankingData.length > 0" class="pagination-container">
          <n-pagination
            v-model:page="currentPage"
            :page-count="Math.ceil(total / pageSize)"
            :page-size="pageSize"
            show-size-picker
            :page-sizes="[10, 20, 50]"
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
          />
        </div>
      </div>
    </div>

    <!-- 物品详情弹窗 -->
    <item-detail-modal
      v-model:show="showDetailModal"
      :object-id="selectedItemId"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useMessage } from 'naive-ui'
import {
  RefreshOutline,
  GridOutline,
  CubeOutline,
  ChevronForwardOutline,
  ArrowBackOutline,
  ArrowUpOutline,
  ArrowDownOutline,
  RemoveOutline
} from '@vicons/ionicons5'
import type { Category } from '@/types/items'
import type { RankingItem, RankingType, TimeRange, RankingResponse } from '@/types/ranking'
import { getCategories } from '@/api/items'
import { getRankingList, RANKING_TYPES } from '@/api/ranking'
import ItemDetailModal from '@/components/ItemDetailModal.vue'
import LoadingSkeleton from '@/components/common/LoadingSkeleton.vue'

// 消息提示实例
const message = useMessage()

// 响应式数据
const loading = ref(false)
const categories = ref<Category[]>([])
const selectedCategory = ref<Category | null>(null)
const selectedSubcategory = ref<string>('')

// 筛选条件
const sortType = ref<RankingType>('highest_price')
const gradeFilter = ref<number | null>(null)
const timeRange = ref<TimeRange>('day')

// 分类排行数据
const categoryRankingLoading = ref(false)
const categoryRankingData = ref<RankingItem[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 物品详情弹窗
const showDetailModal = ref(false)
const selectedItemId = ref(0)

// 子分类选项
const subcategoryOptions = computed(() => {
  if (!selectedCategory.value?.children) return []

  return selectedCategory.value.children.map(child => ({
    label: `${child.second_class_cn || child.second_class} (${child.item_count})`,
    value: child.second_class
  }))
})

// 排序选项
const sortOptions = [
  { label: '最高价格', value: 'highest_price' },
  { label: '最低价格', value: 'lowest_price' },
  { label: '涨幅最大', value: 'increase_percentage' },
  { label: '跌幅最大', value: 'decrease_percentage' },
  { label: '价格变化最大', value: 'price_change_absolute' },
  { label: '金额变化最大', value: 'price_change_max' },
  { label: '金额变化最小', value: 'price_change_min' }
]

// 等级选项
const gradeOptions = [
  { label: '白色 (1级)', value: 1 },
  { label: '绿色 (2级)', value: 2 },
  { label: '蓝色 (3级)', value: 3 },
  { label: '紫色 (4级)', value: 4 },
  { label: '橙色 (5级)', value: 5 },
  { label: '红色 (6级)', value: 6 }
]

// 时间范围选项
const timeRangeOptions = [
  { label: '今日', value: 'day' },
  { label: '本周', value: 'week' },
  { label: '本月', value: 'month' },
  { label: '今年', value: 'year' }
]

// 获取分类数据
const fetchCategories = async (forceRefresh = false) => {
  loading.value = true

  // 如果是强制刷新，先清空现有数据
  if (forceRefresh) {
    categories.value = []
    console.log('🔄 强制刷新分类数据，已清空现有数据')
  }

  try {
    console.log('📡 开始获取分类数据...')
    const response = await getCategories()
    console.log('📡 分类数据响应:', response)

    if (response.code === 1 && response.data) {
      categories.value = response.data.categories || []
      console.log('✅ 分类数据获取成功，共', categories.value.length, '个分类')

      if (forceRefresh) {
        message.success('分类数据刷新成功')
      }
    } else {
      console.error('❌ 分类数据响应异常:', response)
      message.error('获取分类数据失败：' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('❌ 获取分类数据失败:', error)
    message.error('获取分类数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 获取分类排行数据
const fetchCategoryRanking = async (forceRefresh = false) => {
  if (!selectedCategory.value) return

  categoryRankingLoading.value = true

  // 如果是强制刷新，先清空现有数据
  if (forceRefresh) {
    categoryRankingData.value = []
    console.log('🔄 强制刷新分类排行数据，已清空现有数据')
  }

  try {
    const params = {
      type: sortType.value,
      time_range: timeRange.value,
      page: currentPage.value,
      page_size: pageSize.value,
      item_type: selectedSubcategory.value || selectedCategory.value.primary_class,
      grade: gradeFilter.value || undefined
    }

    console.log('📡 开始获取分类排行数据，参数:', params)
    const response = await getRankingList(params)
    console.log('📡 分类排行数据响应:', response)

    if (response.code === 1 && response.data) {
      categoryRankingData.value = (response.data as unknown as RankingResponse).list || []
      total.value = (response.data as unknown as RankingResponse).total || 0
      console.log('✅ 分类排行数据获取成功，共', categoryRankingData.value.length, '条记录')

      if (forceRefresh) {
        message.success('排行数据刷新成功')
      }
    } else {
      console.error('❌ 分类排行数据响应异常:', response)
      message.error('获取排行数据失败：' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('❌ 获取分类排行数据失败:', error)
    message.error('获取排行数据失败，请检查网络连接')
  } finally {
    categoryRankingLoading.value = false
  }
}

// 选择分类
const selectCategory = (category: Category) => {
  selectedCategory.value = category
  selectedSubcategory.value = ''
  sortType.value = 'highest_price'
  gradeFilter.value = null
  timeRange.value = 'day'
  currentPage.value = 1
  fetchCategoryRanking() // 正常加载，不强制刷新
}

// 返回概览
const backToOverview = () => {
  selectedCategory.value = null
  selectedSubcategory.value = ''
  categoryRankingData.value = []
}

// 处理筛选条件变化
const handleSubcategoryChange = () => {
  currentPage.value = 1
  fetchCategoryRanking() // 正常加载，不强制刷新
}

const handleSortChange = () => {
  currentPage.value = 1
  fetchCategoryRanking() // 正常加载，不强制刷新
}

const handleGradeChange = () => {
  currentPage.value = 1
  fetchCategoryRanking() // 正常加载，不强制刷新
}

const handleTimeRangeChange = () => {
  currentPage.value = 1
  fetchCategoryRanking() // 正常加载，不强制刷新
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchCategoryRanking() // 正常加载，不强制刷新
}

const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchCategoryRanking() // 正常加载，不强制刷新
}

// 显示物品详情
const showItemDetail = (itemId: number) => {
  selectedItemId.value = itemId
  showDetailModal.value = true
}

// 刷新数据
const refreshData = () => {
  const startTime = Date.now()
  console.log('🔄 [refreshData] 函数开始执行，时间:', new Date().toLocaleTimeString())

  try {
    console.log('🔄 [refreshData] 检查当前状态...')
    console.log('🔄 [refreshData] selectedCategory.value:', selectedCategory.value)
    console.log('🔄 [refreshData] categories.value.length:', categories.value.length)

    if (selectedCategory.value) {
      console.log('🔄 [refreshData] 准备刷新分类排行数据')
      fetchCategoryRanking(true) // 强制刷新
        .then(() => {
          console.log('✅ [refreshData] 分类排行数据刷新完成，耗时:', Date.now() - startTime, 'ms')
        })
        .catch((error) => {
          console.error('❌ [refreshData] 分类排行数据刷新失败:', error)
          message.error('排行数据刷新失败：' + (error.message || '未知错误'))
        })
    } else {
      console.log('🔄 [refreshData] 准备刷新分类概览数据')
      fetchCategories(true) // 强制刷新
        .then(() => {
          console.log('✅ [refreshData] 分类概览数据刷新完成，耗时:', Date.now() - startTime, 'ms')
        })
        .catch((error) => {
          console.error('❌ [refreshData] 分类概览数据刷新失败:', error)
          message.error('分类数据刷新失败：' + (error.message || '未知错误'))
        })
    }

    console.log('🔄 [refreshData] 函数执行完成，总耗时:', Date.now() - startTime, 'ms')
  } catch (error) {
    console.error('❌ [refreshData] 函数执行异常:', error)
    message.error('刷新功能异常，请稍后重试')
  }
}

// 工具函数
const getCategoryDisplayName = (primaryClass: string): string => {
  const categoryNames: Record<string, string> = {
    'acc': '配件',
    'ammo': '弹药',
    'dagger': '近战武器',
    'exchange': '兑换物品',
    'gun': '枪械',
    'opProps': '战术道具',
    'props': '物品',
    'protect': '防护装备',
    'skin': '皮肤',
    'vehicle': '载具'
  }
  return categoryNames[primaryClass] || primaryClass
}

const getCategoryColor = (primaryClass: string): string => {
  const colors: Record<string, string> = {
    'acc': '#f56c6c',
    'ammo': '#e6a23c',
    'dagger': '#909399',
    'exchange': '#67c23a',
    'gun': '#409eff',
    'opProps': '#9c27b0',
    'props': '#ff9800',
    'protect': '#4caf50',
    'skin': '#e91e63',
    'vehicle': '#795548'
  }
  return colors[primaryClass] || '#18a058'
}

const getRankBadgeClass = (rank: number): string => {
  if (rank === 1) return 'rank-badge rank-first'
  if (rank === 2) return 'rank-badge rank-second'
  if (rank === 3) return 'rank-badge rank-third'
  if (rank <= 10) return 'rank-badge rank-top10'
  return 'rank-badge rank-normal'
}

const getGradeClass = (grade: number): string => {
  return `grade-bg-${grade || 1}`
}

const getGradeText = (grade: number): string => {
  const gradeTexts: Record<number, string> = {
    1: '白色',
    2: '绿色',
    3: '蓝色',
    4: '紫色',
    5: '橙色',
    6: '红色'
  }
  return gradeTexts[grade] || '未知'
}

const formatPrice = (price: number): string => {
  if (price >= 10000) {
    return `${(price / 10000).toFixed(1)}万`
  }
  return price?.toLocaleString() || '0'
}

const formatPriceChange = (change: number): string => {
  const abs = Math.abs(change)
  if (abs >= 10000) {
    return `${(abs / 10000).toFixed(1)}万`
  }
  return abs.toLocaleString()
}

const getPriceChangeClass = (change: number): string => {
  if (change > 0) return 'price-increase'
  if (change < 0) return 'price-decrease'
  return 'price-stable'
}

// 生命周期
onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.category-ranking {
  width: 100%;
  padding: 0;
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
  padding: 20px 0;
  border-bottom: 1px solid var(--n-border-color);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.title-section {
  flex: 1;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: var(--n-text-color-1);
}

.page-description {
  margin: 0;
  color: var(--n-text-color-3);
  font-size: 14px;
}

/* 加载状态 */
.loading-container {
  padding: 20px 0;
}

/* 分类概览 */
.categories-overview {
  margin-bottom: 24px;
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.category-card {
  background: var(--n-card-color);
  border: 1px solid var(--n-border-color);
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.category-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: transparent;
  transition: background 0.3s ease;
}

.category-card:hover {
  border-color: var(--n-primary-color);
  box-shadow: 0 4px 16px rgba(24, 160, 88, 0.15);
  transform: translateY(-2px);
}

.category-card:hover::before {
  background: var(--n-primary-color);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.category-info {
  flex: 1;
}

.category-name {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--n-text-color-1);
}

.category-code {
  margin: 0;
  font-size: 12px;
  color: var(--n-text-color-3);
  font-family: 'Courier New', monospace;
  background: var(--n-color-target);
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.category-icon {
  flex-shrink: 0;
}

.card-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--n-text-color-3);
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: var(--n-text-color-1);
}

.card-footer {
  display: flex;
  justify-content: flex-end;
}

/* 分类详细排行 */
.category-detail {
  width: 100%;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--n-border-color);
}

.detail-title h3 {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--n-text-color-1);
}

.detail-title p {
  margin: 0;
  font-size: 14px;
  color: var(--n-text-color-3);
}

.subcategory-selector {
  margin-bottom: 20px;
}

/* 排行榜列表 */
.ranking-list {
  width: 100%;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.ranking-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.ranking-item {
  display: grid;
  grid-template-columns: auto 1fr auto;
  gap: 16px;
  align-items: flex-start;
  padding: 12px 16px;
  background: var(--n-card-color);
  border: 1px solid var(--n-border-color);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.ranking-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: transparent;
  transition: background 0.3s ease;
}

.ranking-item:hover {
  border-color: var(--n-primary-color);
  box-shadow: 0 4px 16px rgba(24, 160, 88, 0.15);
  transform: translateY(-2px);
}

.ranking-item:hover::before {
  background: var(--n-primary-color);
}

/* 排名区域 */
.rank-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  gap: 4px;
  height: 50px;
}

.rank-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  font-weight: bold;
  font-size: 14px;
  position: relative;
  overflow: hidden;
}

.rank-first {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #8b4513;
  box-shadow: 0 2px 8px rgba(255, 215, 0, 0.3);
}

.rank-second {
  background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
  color: #666;
  box-shadow: 0 2px 8px rgba(192, 192, 192, 0.3);
}

.rank-third {
  background: linear-gradient(135deg, #cd7f32, #daa520);
  color: #fff;
  box-shadow: 0 2px 8px rgba(205, 127, 50, 0.3);
}

.rank-top10 {
  background: var(--n-primary-color-suppl);
  color: var(--n-primary-color);
  border: 1px solid var(--n-primary-color);
}

.rank-normal {
  background: var(--n-card-color);
  color: var(--n-text-color-3);
  border: 1px solid var(--n-border-color);
}

/* 物品信息 */
.item-info {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  flex: 1;
  min-width: 0;
}

.item-image {
  position: relative;
  flex-shrink: 0;
  border-radius: 8px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 0;
  overflow: hidden;
  width: 72px;
  height: 72px;
}

.item-image .n-avatar {
  display: block;
  border-radius: 8px !important;
  margin: 0 !important;
  padding: 0 !important;
  vertical-align: top;
}

/* 确保等级边框也有圆角 */
.item-image .grade-bg-1,
.item-image .grade-bg-2,
.item-image .grade-bg-3,
.item-image .grade-bg-4,
.item-image .grade-bg-5,
.item-image .grade-bg-6 {
  border-radius: 8px !important;
}

.item-details {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.item-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--n-text-color-1);
  line-height: 1.3;
  word-break: break-word;
}

.item-meta {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.item-grade,
.item-category {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
  background: var(--n-color-target);
  color: var(--n-text-color-2);
  line-height: 1.2;
}

/* 筛选器 */
.filters-section {
  margin-bottom: 12px;
}

.filters-container {
  background: var(--n-card-color);
  border: 1px solid var(--n-border-color);
  border-radius: 8px;
  padding: 12px 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.filters-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)) auto;
  gap: 12px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.filter-label {
  font-size: 13px;
  font-weight: 500;
  color: var(--n-text-color-2);
  white-space: nowrap;
  flex-shrink: 0;
  min-width: 50px;
}

.filter-actions {
  display: flex;
  align-items: center;
  justify-self: end;
}

/* 价格信息 */
.price-section {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  min-width: 280px;
  padding: 8px 10px;
  background: var(--n-color-target);
  border-radius: 6px;
  border: 1px solid var(--n-border-color);
}

.price-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.current-price {
  display: flex;
  flex-direction: column;
  gap: 1px;
}

.price-label {
  font-size: 13px;
  color: var(--n-text-color-3);
  font-weight: 500;
  line-height: 1.2;
}

.price-value {
  font-size: 20px;
  font-weight: 700;
  color: var(--n-text-color-1);
  line-height: 1.2;
}

.price-change {
  display: flex;
  align-items: center;
  gap: 3px;
  font-size: 14px;
  font-weight: 600;
  line-height: 1.2;
}

.change-text {
  display: flex;
  align-items: center;
  gap: 3px;
}

.change-percent {
  font-weight: 600;
}

.yesterday-price {
  font-size: 12px;
  color: var(--n-text-color-3);
  line-height: 1.2;
}

.yesterday-value {
  font-weight: 500;
  color: var(--n-text-color-2);
}

.price-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1px;
  align-items: flex-end;
}

.compare-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  gap: 6px;
}

.compare-label {
  font-size: 12px;
  color: var(--n-text-color-3);
  font-weight: 500;
  line-height: 1.2;
}

.compare-value {
  font-size: 13px;
  font-weight: 600;
  color: var(--n-text-color-1);
  line-height: 1.2;
}

.compare-percent {
  font-size: 11px;
  font-weight: 600;
  margin-left: 6px;
  line-height: 1.2;
}

.price-increase {
  color: #18a058;
}

.price-decrease {
  color: #d03050;
}

.price-stable {
  color: var(--n-text-color-3);
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid var(--n-border-color);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
  }

  .categories-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .category-card {
    padding: 16px;
  }

  .card-stats {
    gap: 16px;
  }

  .detail-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .filters-container {
    padding: 10px 12px;
  }

  .filters-row {
    grid-template-columns: 1fr;
    gap: 10px;
  }

  .filter-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .filter-label {
    min-width: auto;
    font-size: 12px;
  }

  .filter-actions {
    justify-self: stretch;
  }

  .filter-actions .n-button {
    width: 100%;
  }

  .ranking-item {
    grid-template-columns: auto 1fr;
    gap: 12px;
  }

  .price-section {
    grid-column: 1 / -1;
    flex-direction: column;
    gap: 8px;
    margin-top: 12px;
    padding: 8px;
    border-top: 1px solid var(--n-border-color);
    min-width: auto;
  }

  .price-left,
  .price-right {
    flex: none;
    width: 100%;
  }

  .price-right {
    align-items: flex-start;
  }

  .price-label {
    font-size: 12px;
  }

  .price-value {
    font-size: 18px;
  }

  .price-change {
    font-size: 12px;
  }

  .yesterday-price {
    font-size: 11px;
  }

  .compare-label {
    font-size: 11px;
  }

  .compare-value {
    font-size: 12px;
  }

  .compare-percent {
    font-size: 10px;
  }
}
</style>
